import os
import time
import sys

write_path = "/tmp/motor_pipe.in"
# read_path = "/tmp/motor_pipe.out"


# 打印所有命令行参数
# print(f"所有命令行参数:[{len(sys.argv)}]", sys.argv)


if len(sys.argv) != 2:
    print("Usage:")
    print("python3 fifo_client.py [CH | CB | 9H | 6H | 3H | 12H]")
    sys.exit()

msg = sys.argv[1]

if not os.path.exists(write_path):
    print(f"[{write_path}] 管道不存在")
    sys.exit()

# 需要有换行符号 "\n"
#with open(write_path, 'w') as pipe:
#    pipe.write(msg + "\n")

wf = os.open(write_path, os.O_SYNC | os.O_CREAT | os.O_RDWR)
# rf = None


len_send = os.write(wf, str.encode(msg + "\n"))

os.close(wf)



# while True:
#     msg = input("input cmd >")
#     print("cmd > ", msg)
#     len_send = os.write(wf, str.encode(msg))
#     time.sleep(1)

# os.close(rf)
# os.close(wf)



# b = b"example"    # bytes object  
# s = "example"     # str object  
# sb = bytes(s, encoding = "utf8")    # str to bytes 
# 或者：sb = str.encode(s)             # str to bytes 
# bs = str(b, encoding = "utf8")      # bytes to str  
# 或者：bs = bytes.decode(b)           #  bytes to str  


# for i in range(1, 11):
#     msg = "msg " + str(i)
#     len_send = os.write(wf, str.encode(msg))
#     print(f"sent msg: {msg}")

#     if rf is None:
#         rf = os.open(read_path, os.O_RDONLY)

#     # os.read() 读取的为字节流，需要转成字符串
#     s = bytes.decode(os.read(rf, 1024))
#     if len(s) == 0:
#         break
    
#     print(f"received msg: {s}")

#     time.sleep(1)

# # os.write 需要写入 bytes
# os.write(wf, str.encode('exit'))

# os.close(rf)
# os.close(wf)
